import 'dart:io';

import 'package:chatgreat/helper/color.dart';
import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/helper/my_widget.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/sliver_component.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/page/setting/setting_screen.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
// import 'package:stripe_js/stripe_js.dart';

import '../../../repo/api_server.dart';
import '../../helper/upload.dart';
import '../component/dialog.dart';
import '../component/enhanced_textfield.dart';

class FeedBackScreen extends StatefulWidget {
  final SettingRepository setting;

  const FeedBackScreen(
      {super.key, required this.setting,});

  @override
  State<FeedBackScreen> createState() => _FeedBackScreenState();
}

enum GenerateStatus { display, generating, over }

class _FeedBackScreenState extends State<FeedBackScreen> {
  final TextEditingController _titleTextController = TextEditingController();
  final TextEditingController _contentTextController = TextEditingController();

  List<XFile> selectedImageFiles = [];
  bool enableNotifier = true;

  @override
  void initState() {
    super.initState();

  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return BackgroundContainer(
      setting: widget.setting,
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: _buildFeedbackWidget(customColors),
        ),
      ),
    );
  }

  /// 反馈问题
  Widget _buildFeedbackWidget(
      CustomColors customColors,
      ) {
    return SliverCreateComponent(
      title: const Text(
        "反馈问题",
        style: TextStyle(
          fontSize: CustomSize.appBarTitleSize,
          color: Colors.white,
        ),
      ),
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back,
          color: customColors.weakLinkColor,
        ),
        onPressed: () {
          if (context.canPop()) {
            context.pop();
          }
        },
      ),
      child: Column(
        children: [
          Expanded(
            child: ListView(
              padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 22),
              shrinkWrap: true,
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 2),
                  child: MyTextWeight('问题主题', 16, Colors.white, FontWeight.w400),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 12, bottom: 43),
                  padding: const EdgeInsets.only(left: 15, right: 10),
                  height: 75,
                  decoration: BoxDecoration(
                    color: stringToColor('FF21222F'),
                    borderRadius: BorderRadius.circular(6.0),
                  ),
                  child: EnhancedTextField(
                    onFocusChange: (hasFocus) {},
                    controller: _titleTextController,
                    enabled: enableNotifier,
                    customColors: customColors,
                    maxLines: 2,
                    hintText: '这里输入问题的主题~',
                    maxLength: 40,
                    showCounter: false,
                    keyboardType: TextInputType.text,
                    hintColor: const Color(0xFF999999),
                    hintTextSize: 15,
                  ),
                ),
            
                Padding(
                  padding: const EdgeInsets.only(left: 2),
                  child: MyTextWeight('问题描述', 16, Colors.white, FontWeight.w400),
                ),
            
                Container(
                  margin: const EdgeInsets.only(top: 12, bottom: 43),
                  padding: const EdgeInsets.only(left: 15, right: 10),
                  height: 183,
                  decoration: BoxDecoration(
                    color: stringToColor('FF21222F'),
                    borderRadius: BorderRadius.circular(6.0),
                  ),
                  child: EnhancedTextField(
                    onFocusChange: (hasFocus) {},
                    controller: _contentTextController,
                    enabled: enableNotifier,
                    customColors: customColors,
                    maxLines: 6,
                    hintText: '这里输入反馈的具体内容，帮我们核实情况',
                    maxLength: 500,
                    showCounter: true,
                    keyboardType: TextInputType.text,
                    hintColor: const Color(0xFF999999),
                    hintTextSize: 15,
                  ),
                ),
            
                if (selectedImageFiles.isNotEmpty)
                  SizedBox(
                    height: 110,
                    child: ListView(
                      scrollDirection: Axis.horizontal,
                      children: selectedImageFiles
                          .map(
                            (e) => Container(
                          margin: const EdgeInsets.only(right: 8),
                          padding: const EdgeInsets.all(5),
                          child: Stack(
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(3),
                                child: Image.file(
                                  File(e.path),
                                  fit: BoxFit.cover,
                                  width: 70,
                                  height: 70,
                                ),
                              ),
                              Positioned(
                                right: 0,
                                top: 0,
                                child: InkWell(
                                  onTap: () {
                                    setState(() {
                                      selectedImageFiles.remove(e);
                                    });
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.all(3),
                                    decoration: BoxDecoration(
                                      borderRadius:
                                      BorderRadius.circular(10),
                                      color: Colors.transparent,
                                    ),
                                    child: imgWidget(17, 17, 'shanchu'),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      )
                          .toList(),
                    ),
                  ),
            
                Container(
                  alignment: Alignment.centerLeft,
                  height: 70,
                  child: InkWell(
                    onTap: () async {
                      PermissionStatus status = await Permission.photos.status;
                      if (!status.isGranted) {
                        // 请求相册权限
                        status = await Permission.photos.request();
                        if (!status.isGranted) {
                          showJurisdictionDialog(context, 1);
                          return;
                        }
                      }

                      // 上传图片
                      if (selectedImageFiles.length >= 1) {
                        showSuccessMessage('最多只能上传 1 张图片');
                        return;
                      }
            
                      XFile? pickedImage = await ImagePicker().pickImage(source: ImageSource.gallery);
                      if (pickedImage != null) {
                        final files = selectedImageFiles;
                        files.add(pickedImage);
                        setState(() {
                          selectedImageFiles = files.sublist(0, files.length > 1 ? 1 : files.length);
                        });
                      }
                    },
                    child: DottedBorder(
                      borderType: BorderType.RRect,
                      radius: const Radius.circular(3),
                      color: stringToColor('FFCCCCCC'),
                      strokeWidth: 0.5,
                      child: Container(
                        alignment: Alignment.center,
                        width: 70,
                        height: 70,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            imgWidget(23, 20, 'camera'),
                            const SizedBox(height: 8,),
                            MyTextWeight('添加图片', 12, stringToColor('FF999999'), FontWeight.w500)
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          Container(
            margin: const EdgeInsets.only(left: 19, right: 19, bottom: 32),
            width: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/guide_button.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: TextButton(
              child: MyTextWeight('提交', 16, Colors.white, FontWeight.normal),
              onPressed: () async {
                String title = _titleTextController.text;
                String content = _contentTextController.text;
                if (isBlank(title)) {
                  showErrorMessage('请输入问题主题');
                  return;
                }
                if (isBlank(content)) {
                  showErrorMessage('请输入问题描述');
                  return;
                }
                
                List<String> urlList = [];
                EasyLoading.show(status: '请稍等...');
                for (var element in selectedImageFiles) {
                  var imgFile = File(element.path);
                  var uploader = await QiniuUploader(widget.setting).uploadFile(imgFile);
                  urlList.add(uploader.url);
                }
                // String url = urlList.join(',');
                String url = urlList.first;

                APIServer().submitFeedback(title, content, url).then((value) {
                  EasyLoading.dismiss();

                  if (context.canPop()) {
                    context.pop();
                  }
                  Future.delayed(const Duration(milliseconds: 700)).then((value) => showSuccessMessage('已提交，感谢您的反馈'));
                }).catchError((e) {
                  EasyLoading.dismiss();
                });
              },
            ),
          ),
        ],
      ),
    );
  }

}
